<template>
    <el-container>
        <el-aside width="230px" v-loading="menuLoading">
            <el-container>
                <el-main class="nopadding">
                    <el-tree ref="menuRef" class="menu" :data="menu" node-key="id" :props="menuProps"
                        :current-node-key="currentNodeKey" :default-expanded-keys="[0]" highlight-current accordion
                        @node-click="menuClick"></el-tree>
                </el-main>
            </el-container>
        </el-aside>
        <el-container class="is-vertical">
            <el-header>
                <div class="left-panel">
                    <el-button type="primary" @click="upload">本地上传</el-button>
                    <el-button plain @click="folderAdd">新建文件夹</el-button>
                    <el-dropdown>
                        <el-button plain>清理文件<el-icon class="arrowdown"><el-icon-arrow-down /></el-icon></el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item>删除全部未引用文件</el-dropdown-item>
                                <el-dropdown-item>删除90天内未引用文件</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
                <div class="right-panel">
                    <div class="group">
                        <el-radio-group v-model="group">
                            <el-radio-button label="all">全部</el-radio-button>
                            <el-radio-button label="image">图片</el-radio-button>
                            <el-radio-button label="video">视频</el-radio-button>
                        </el-radio-group>
                    </div>
                    <div class="search">
                        <el-input v-model="search.name" placeholder="请输入素材名称" clearable size="small">
                            <template #append>
                                <el-button @click="upsearch">查询</el-button>
                            </template>
                        </el-input>
                    </div>
                </div>
            </el-header>
            <el-header class="topbar">
                <div class="left-panel">
                    <el-breadcrumb separator-icon="el-icon-arrow-right">
                        <el-breadcrumb-item :class="{ 'font-bold': item.id === selectedItemId }" v-for="item in breadcrumbs"
                            :key="item.id" @click="folderClick(item)">{{
                                item.label }}</el-breadcrumb-item>
                    </el-breadcrumb>
                </div>
            </el-header>
            <el-main class="nopadding">
                <scTable ref="tableRef" :apiObj="apiObj" :hideOperation="hideOperation" @selection-change="selectionChange"
                    border stripe remoteSort remoteFilter :hideSetting="true">
                    <el-table-column type="selection" width="50" align="center"></el-table-column>
                    <el-table-column label="素材名称" prop="name" width="230">
                        <template #default="scope">
                            <div class="name">
                                <div class="name_image">
                                    <el-icon v-if="scope.row.type == 'folder'" class="folder"
                                        @click="folderClick(scope.row)"><sc-icon-folder /></el-icon>
                                    <img v-else class="file" :src="scope.row.path">
                                </div>
                                <div class="name_text">
                                    {{ scope.row.name }}
                                    <el-popover title="重命名" :visible="activePopover === scope.row.id" placement="top"
                                        :width="250" trigger="click">
                                        <el-input v-model="editingName" maxlength="20" show-word-limit
                                            placeholder="输入新名称"></el-input>
                                        <div style="text-align: right; padding-top: 10px">
                                            <el-button size="small" text @click="activePopover=false">取消</el-button>
                                            <el-button v-if="scope.row.type == 'folder'" size="small" type="primary"
                                                @click="folderEdit(scope.row)">确认</el-button>
                                            <el-button v-if="scope.row.type == 'file'" size="small" type="primary"
                                                @click="fileEdit(scope.row)">确认</el-button>
                                        </div>
                                        <template #reference>
                                            <el-button class="edit" text type="primary" size="small"
                                                @click="togglePopover(scope.row)"><el-icon><sc-icon-edit /></el-icon></el-button>
                                        </template>
                                    </el-popover>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="大小" prop="size" width="109" sortable='custom' align="center"></el-table-column>
                    <el-table-column label="尺寸" prop="dimension" width="100" align="center"></el-table-column>
                    <el-table-column label="上传时间" prop="create_at" width="150" sortable='custom'
                        align="center"></el-table-column>
                    <el-table-column label="状态" prop="status" width="100" sortable='custom' align="center">
                        <template #default="scope">
                            <div v-if="scope.row.type == 'file'">
                                <el-tag v-if="scope.row.status == 1">上传成功</el-tag>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="是否引用" prop="quote_count" width="120" align="center">
                        <template #default="scope">
                            <div v-if="scope.row.type == 'file'">
                                <el-tag type="success" v-if="scope.row.quote_count > 0">已引用</el-tag>
                                <el-tag type="danger" v-else>未引用</el-tag>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" fixed="right" width="140" align="center">
                        <template #default="scope">
                            <el-button-group>
                                <el-popconfirm v-if="scope.row.type == 'folder'" title="删除文件夹及文件夹下的所有文件" width='260'
                                    @confirm="folder_del(scope.row, scope.$index)">
                                    <template #reference>
                                        <el-button v-auth="'user.delete'" text type="primary" size="small">{{
                                            $t('common.del') }}</el-button>
                                    </template>
                                </el-popconfirm>
                                <el-popconfirm v-if="scope.row.type == 'file'" :title="$t('common.confirmRemove')"
                                    width='260' @confirm="file_del(scope.row, scope.$index)">
                                    <template #reference>
                                        <el-button v-auth="'user.delete'" text type="primary" size="small">{{
                                            $t('common.del') }}</el-button>
                                    </template>
                                </el-popconfirm>
                                <el-button v-auth="'user.edit'" text type="primary" size="small"
                                    @click="file_move(scope.row)">移动至</el-button>
                            </el-button-group>
                        </template>
                    </el-table-column>
                    <template #operation>
                        <div class="scTable-operation flex">
                            <el-checkbox v-model="checkAll" @change="handleCheckAllChange"
                                :disabled="disabled">全选</el-checkbox>
                            <el-button :disabled="selection.length == 0" plain @click="batch_move">批量移动</el-button>
                            <el-button :disabled="selection.length == 0" plain @click="batch_del">批量删除</el-button>
                        </div>
                    </template>
                </scTable>
            </el-main>
        </el-container>
    </el-container>
    <save-dialog v-if="dialog.save" ref="saveDialogRef" @success="handleSaveSuccess"
        @closed="dialog.save = false"></save-dialog>
    <move-dialog v-if="dialog.move" ref="moveDialogRef" :menus="menu" @success="handleMoveSuccess"
        @closed="dialog.move = false"></move-dialog>
    <file-dialog v-if="dialog.file" ref="fileDialogRef" @file-list="handleFileList"
        @closed="dialog.file = false"></file-dialog>
    <process-dialog v-if="dialog.process" ref="processDialogRef" @back-to-file="handleBackToFile"
        @closed="dialog.file = false"></process-dialog>
</template>
<script setup>
import { ref, reactive, watch, computed, onMounted, nextTick } from 'vue';
import api from '@/api';
import i18n from '@/locales';
import { ElMessage, ElMessageBox } from 'element-plus';
import saveDialog from './save.vue';
import moveDialog from './move.vue';
import fileDialog from './file.vue';
import processDialog from './process.vue';

// 菜单、表格和对话框相关的响应式引用
const menuID = ref(0);
const selectedItemId = ref(0);
const menuLoading = ref(false);
const menuRef = ref(null);
const tableRef = ref(null);
const saveDialogRef = ref(null);
const moveDialogRef = ref(null);
const fileDialogRef = ref(null);
const processDialogRef = ref(null);
const menu = ref([]);
const hideOperation = ref(true);
const menuProps = reactive({ value: "id", label: "name" });
// 界面相关的属性和配置
const group = ref('all');
const search = reactive({ name: null });
const apiObj = ref(api.common.file.list);
const currentNodeKey = ref(0);
const dialog = reactive({ save: false, move: false, file: false, process: false });
const checkAll = ref(false);
const selection = ref([]);
const disabled = computed(() => tableRef.value && tableRef.value.tableData.length === 0);
const breadcrumbs = ref([{ label: '全部文件', id: 0 }]);
const activePopover = ref(null);
// 用于存储正在编辑的名称
const editingName = ref('');
// 组件挂载时执行的操作
onMounted(() => {
    getFolder();
});
// 切换弹出窗口的可见性
const togglePopover = (row) => {
    activePopover.value = activePopover.value === row.id ? null : row.id;
    editingName.value = row.name;
};
// 获取文件夹数据的方法
const getFolder = async () => {
    menuLoading.value = true;
    const res = await api.common.folder.list.get();
    if (res.code == 200) {
        const options = [
            { id: 0, name: '全部文件', children: res.data },
        ];
        menu.value = options;
    }
    menuLoading.value = false;
};
// 菜单项点击事件处理
const menuClick = (node, event) => {
    if (node.id === 0 || event.childNodes.length !== 0) {
        event.expanded = true;
    }
    menuID.value = node.id;
    var params = { pid: node.id };
    tableRef.value.reload(params);
    const path = findNodePath(menu.value, node.id);
    breadcrumbs.value = path || [{ label: '全部文件', id: 0 }];
    selectedItemId.value = node.id;
};
// 在树状结构中递归查找并返回到指定节点的路径
const findNodePath = (menu, nodeId, path = []) => {
    for (let node of menu) {
        const newPath = [...path, { label: node.name, id: node.id }];
        if (node.id === nodeId) {
            return newPath;
        }
        if (node.children && node.children.length) {
            const result = findNodePath(node.children, nodeId, newPath);
            if (result) return result; // 早期返回，避免不必要的遍历
        }
    }
    return null;
};
// 文件夹点击事件处理
const folderClick = (row) => {
    if (row.id !== selectedItemId.value) {
        var params = { pid: row.id };
        tableRef.value.reload(params);
        const path = findNodePath(menu.value, row.id);
        breadcrumbs.value = path || [{ label: '全部文件', id: 0 }];
        selectedItemId.value = row.id;
        menuID.value = row.id;
        nextTick(() => {
            menuRef.value.setCurrentKey(row.id);
        })
    }
}
// 文件上传事件处理
const upload = () => {
    dialog.file = true;
    nextTick(() => {
        fileDialogRef.value.open('file', menuID.value);
    });
};
// 新建文件夹事件处理
const folderAdd = () => {
    dialog.save = true;
    nextTick(() => {
        saveDialogRef.value.open('add', menuID.value);
    });
};
// 编辑文件夹事件处理
const folderEdit = async (row) => {
    const form = { id: row.id, name: editingName.value, };
    const res = await api.common.folder.edit.post(form);
    if (res.code == 200) {
        activePopover.value = false;
        await getFolder();
        tableRef.value.refresh();
        menuRef.value.setCurrentKey(selectedItemId.value);
    }
};
// 文件编辑事件处理
const fileEdit = async (row) => {
    const form = { id: row.id, name: editingName.value, };
    const res = await api.common.file.edit.post(form);
    if (res.code == 200) {
        activePopover.value = false;
        tableRef.value.refresh();
    }
};
// 搜索逻辑处理
const upsearch = () => tableRef.value.upData(search);
// 文件夹删除事件处理
const folder_del = async (row, index) => {
    const reqData = { ids: [row.id] };
    const res = await api.common.folder.delete.delete(reqData);
    if (res.code == 200) {
        menuRef.value.remove(row.id);
        tableRef.value.tableData.splice(index, 1);
        ElMessage.success(res.message);
    } else {
        ElMessage.error(res.message);
    }
};
// 文件删除事件处理
const file_del = async (row, index) => {
    const reqData = { ids: [row.id] };
    const res = await api.common.file.delete.delete(reqData);
    if (res.code == 200) {
        tableRef.value.tableData.splice(index, 1);
        ElMessage.success(res.message);
    } else {
        ElMessage.error(res.message);
    }
};
const file_move = (row) => {
    dialog.move = true;
    nextTick(() => {
        moveDialogRef.value.open('move');
        moveDialogRef.value.setData({ id: [row.id] });
    });
};
// 批量移动事件处理
const batch_move = () => {
    const ids = selection.value.map(item => item.id);
    console.log(ids);
    dialog.move = true;
    nextTick(() => {
        moveDialogRef.value.open('move');
        moveDialogRef.value.setData({ id: ids });
    });
};
// 批量删除事件处理
const batch_del = () => {
    ElMessageBox.confirm(i18n.global.t('common.confirmDelete', { count: selection.value.length }), i18n.global.t('common.tip'), {
        type: 'warning',
    }).then(async () => {
        const ids = selection.value.map(item => item.id);
        const res = await api.common.folder.delete.delete({ ids });
        if (res.code == 200) {
            selection.value.forEach(item => {
                menuRef.value.remove(item.id);
                tableRef.value.tableData.forEach((itemI, indexI) => {
                    if (item.id === itemI.id) {
                        tableRef.value.tableData.splice(indexI, 1);
                    }
                })
            })
            ElMessage.success(res.message);
        } else {
            ElMessage.error(res.message);
        }
    })
};
// 表格选择变化事件处理
const selectionChange = (val) => {
    selection.value = val;
    checkAll.value = val.length === tableRef.value.tableData.length;
};
// 全选框变化处理
const handleCheckAllChange = (val) => {
    if (val) {
        tableRef.value.toggleAllSelection();
    } else {
        tableRef.value.clearSelection();
    }
};
// 保存成功后的处理
const handleSaveSuccess = (mode) => {
    if (mode === 'add') {
        // 在整个树中搜索并更新节点
        getFolder();
        tableRef.value.refresh();
    }
};
// 移动成功后的处理
const handleMoveSuccess = async () => {
    await getFolder();
    menuRef.value.setCurrentKey(selectedItemId.value);
    // 刷新表格视图
    tableRef.value.refresh();
};
// 获取文件列表
const handleFileList = (fileList) => {
    dialog.file = false;
    dialog.process = true;
    nextTick(() => {
        processDialogRef.value.open(fileList, menuID.value);
    });
};
// 文件上传处理
const handleBackToFile = () => {
    dialog.process = false;
    dialog.file = true;
    nextTick(() => {
        fileDialogRef.value.open();
    });
};
// 监听筛选组的变化
watch(group, async (newValue) => {
    // console.log(tableRef.value);
    // tableRef.value.tableData.filter(item => item.type === newValue);
}, { immediate: true });
</script>
<style scoped>
label+.el-button {
    margin-left: 12px;
}

.arrowdown {
    @apply ml-1;
}

.topbar {
    height: 20px;
}

.topbar :deep(.el-breadcrumb .el-breadcrumb__inner) {
    cursor: pointer;
}

.topbar :deep(.font-bold .el-breadcrumb__inner) {
    font-weight: bold;
    cursor: unset;
}

.el-tree-node__label,
.name,
.name .name_image {
    display: flex;
}

.name .name_text {
    display: flex;
    align-items: center;
    justify-content: center;
}

.name .el-icon.folder {
    font-size: 32px;
    color: rgb(99, 206, 255);
    cursor: pointer;
    margin-right: 5px;
    flex-shrink: 0;
}

.name img.file {
    width: 32px;
    height: 32px;
    cursor: pointer;
    margin-right: 5px;
    flex-shrink: 0;
}

.name .edit {
    display: flex;
    font-size: 12px;
    color: rgb(12, 76, 130);
    cursor: pointer;
    margin-left: 15px;
}
</style>
